package com.example.myapplicationktkt2.model

import androidx.lifecycle.*
import kotlinx.coroutines.launch
import java.util.*

class AdvancedUserViewModel : ViewModel() {
    // 基础的 MutableLiveData 数据
    private val _firstName = MutableLiveData<String>()
    private val _lastName = MutableLiveData<String>()
    private val _age = MutableLiveData<Int>()
    
    val firstName: LiveData<String> = _firstName
    val lastName: LiveData<String> = _lastName
    val age: LiveData<Int> = _age
    
    // 使用 Transformations.map 创建计算属性 - 全名
    val fullName: LiveData<String> = _firstName.switchMap { firstName ->
        _lastName.map { lastName ->
            "$firstName $lastName"
        }
    }
    
    // 使用 Transformations.switchMap 根据年龄计算用户类型
    val userType: LiveData<String> = _age.switchMap { age ->
        val type = when {
            age!! < 13 -> "儿童"
            age < 20 -> "青少年"
            age < 60 -> "成年人"
            else -> "老年人"
        }
        MutableLiveData(type)
    }
    
    // 使用 MediatorLiveData 合并多个数据源
    val userSummary: MediatorLiveData<String> = MediatorLiveData<String>().apply {
        addSource(firstName) { value = generateSummary() }
        addSource(lastName) { value = generateSummary() }
        addSource(age) { value = generateSummary() }
    }
    
    private fun generateSummary(): String {
        val first = _firstName.value ?: ""
        val last = _lastName.value ?: ""
        val userAge = _age.value ?: 0
        
        return if (first.isNotEmpty() || last.isNotEmpty()) {
            "用户: $first $last, 年龄: $userAge"
        } else {
            "用户信息未设置"
        }
    }
    
    // 更新数据的方法
    fun updateFirstName(name: String) {
        _firstName.value = name
    }
    
    fun updateLastName(name: String) {
        _lastName.value = name
    }
    
    fun updateAge(age: Int) {
        _age.value = age
    }
    
    // 模拟异步数据加载
    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading
    
    private val _userData = MutableLiveData<String>()
    val userData: LiveData<String> = _userData
    
    fun loadUserData() {
        _isLoading.value = true
        
        // 模拟网络请求
        viewModelScope.launch {
            // 延迟1秒模拟网络请求
            kotlinx.coroutines.delay(1000)
            _userData.value = "加载的用户数据: ${Date()}"
            _isLoading.value = false
        }
    }
}